import json

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from user.models import UserModel,RoleModel,ResourceModel,InterfacePerModel
import re
import random
import time
from tools.common import send_message
from tools.myredis import r
from tools.myjwt import mjwt
from user.serializer.ser import UserSerializer,RoleSerializer,ResourceSerializer
from base.tasks import celery_test

# Create your views here.
# Test
class TestView(APIView):
    def get(self, request):
        print("TestView--------->")
        celery_test.delay()
        print("TestView----time----",int(time.time()))
        return Response({"message":"测试 Celery Test"})

# 账号密码登录
class LoginView(APIView):
    def post(self, request):
        # 获取参数
        # username = request.data.get('username', None)
        # password = request.data.get('password', None)
        phone = request.data.get('phone', None)
        # 验证码

        # 查询user表
        print(phone)
        user = UserModel.objects.filter(phone__exact=phone).first()
        reso = user.role.resource.all()
        # print(user)
        # print(reso)
        # 构建父类资源/资源信息重组、
        rlist = []
        idlist = []
        interlist=[] #接口权限列表
        for i in reso:
            # 获取此资源的所有接口
            interfaces = i.interfaces.all()
            for interface in interfaces:
                interlist.append(interface.url)

            pid = i.pid.id
            if pid not in idlist:
                rlist.append({"id":pid,"name":i.pid.name,'son':[]})
                idlist.append(pid)

        # 遍历rlist
        for index,i in enumerate(rlist):
            #遍历res
            for j in reso:
                # 找到父类的son
                if j.pid.id == i['id']:
                    rlist[index]['son'].append({"id":j.id,'name':j.name,'url':j.url})
        print("rlist--->")
        print(rlist)
        print("idlist--->")
        print(idlist)
        print("iplist---->")
        print(interlist)

        r.set_str('user'+str(user.id)+'interface',json.dumps(interlist))

        # if not user:
        #     return Response({"code":"2001",'message': 'User not found'})
        # if password != user.password:
        #     return Response({"code":"2002",'message': 'Wrong password'})
        token = mjwt.jwt_encode({"userid":user.id,'exp':int(time.time())+3600})
        return Response({"code":"200",'message': 'Successfully logged in',"token":token,"rlist":rlist})

# Create your views here.

# 发送验证码/获取验证码接口
class SendMobileCodeView(APIView):
    def get(self, request):
        # send_sms前端： /sendsms/?phone=${this.account}/
        phone = request.GET.get('phone')
        print(phone)
        if not re.match(r"1[3-9]\d{9}$",phone):
            return Response({"message":"手机号验证失败！","code":"410"})
        # r.get_str("flag")
        sms_code = random.randint(1000,9999)
        print("sms_code--------------------------->" + str(sms_code))
        r.delete_str("sms_code")
        r.setex_str("sms_code",60*5,sms_code) # times：5分钟有效期
        flag = send_message(phone, sms_code)
        # r.set_str("phone",60,"1024")
        return Response({"message":"发送成功","code":"200"})
        # return Response({"message":"发送成功","code":"200","sms_code":sms_code})

# 手机短信登录接口
class MobileLoginView(APIView):
    def post(self, request):
        myphone = request.data.get("mobile")
        mycode = request.data.get("code")
        sms_code = r.get_str("sms_code")

        print("r.get_str------------->" + str(sms_code))
        if mycode == sms_code:
            user = UserModel.objects.filter(phone=myphone).first()
            print("user------>")
            print(user)
            # user = {"phone":myphone,"code":mycode}
            # user = {"phone":"18631290000","code":"1234"}
            token = mjwt.jwt_encode({"userid":user.id,"exp":int(time.time()) + 3600})
            return Response({"code":200,"token":token,"userid":user.id})
        else:
            return Response({"code":4001,"message":"验证码错误！"})

# --------------------------------------------


# 获取角色对应信息
class RoleView(APIView):
    def get(self, request):
        data = RoleModel.objects.all()
        roleSer = RoleSerializer(data, many=True)
        return Response({"message":"获取角色资源对应信息","code":200,"data":roleSer.data})

class ResourceView(APIView):
    def get(self, request):
        # 拿 roleid
        # 拿 roleid 对应的资源,
        roleid = request.GET.get('roleid')
        res = ResourceModel.objects.filter(pid_id__gt=0).all()
        # transf -- key -- label
        allres = [{"key":i.id,"label":i.name} for i in res] #pid>0，所有资源

        role = RoleModel.objects.filter(id=roleid).first()
        checkres = role.resource.all() #拿这个角色对应的所有资源(选中)
        checkedids = [i.id for i in checkres] #拿对应的所有资源id(选中)
        return Response({"code":200,"allres":allres,"checkedids":checkedids})

    def post(self, request):
        resids = request.data.get("resids")
        roleid = request.data.get("roleid")
        role = RoleModel.objects.filter(id=roleid).first()
        print(role.resource.all())
        if role.resource.all():
            role.resource.clear()#清除之前存在的所有资源
        role.resource.add(*resids)#添加传进来的 资源 ids
        return Response({"code":200})